const mongoose = require('mongoose');
const News = require('../models/news-models');
//新增
exports.create = function(req, res, next) {
        const news = new News(req.body);
        news.save().then((data) => {
            res.json(data);
        });
    }
    //修改
exports.update = function(req, res, next) {
        const id = req.params.id;
        News.findByIdAndUpdate(id, { $set: req.body }, { new: false }).then(data => { //new:false 如果通过id没找到就重新创建一个
            res.json(data); //返回的是修改之前的数据
        })
    }
    //删除
exports.remove = function(req, res, next) {
        const id = req.params.id;
        News.findByIdAndDelete(id, (err, data) => {
            res.json(data);
        })
    }
    //查询
exports.list = function(req, res, next) {
    var page = req.body.page ? req.body.page : 1;
    var limit = req.body.limit ? req.body.limit : 5;

    var queryCondition = {}; //查询条件
    if (req.body.name && req.body.name.trim().length > 0) {
        name = req.body.name;
        queryCondition = {
            'name': new RegExp(name, 'i')
        }
    }
    News.paginate(queryCondition, { page: +page, limit: +limit }, function(err, result) {
        res.json(result);
    });
}